package com.ojoin.trade.common_core.web.service.impl;

import java.math.BigDecimal;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ojoin.trade.common.utils.*;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.TbWeekend;
import com.ojoin.trade.common.web.domain.Result.Status;
import com.ojoin.trade.common.web.service.TbWeekEndService;
import com.ojoin.trade.common.web.service.impl.HotConfigService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ojoin.trade.common.Constants;
import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.exception.IPayNowException;
import com.ojoin.trade.common.utils.json.JSONUtils;
import com.ojoin.trade.common.utils.paynow.HttpPost;
import com.ojoin.trade.common.utils.paynow.IAccountConst;
import com.ojoin.trade.common.utils.paynow.Packages;
import com.ojoin.trade.common.utils.paynow.Unpack;
import com.ojoin.trade.common_core.web.domain.TbMerchantInfo;
import com.ojoin.trade.common_core.web.domain.TbTransferTokenStatus;
import com.ojoin.trade.common_core.web.service.AccountBaseService;
import com.ojoin.trade.common_core.web.service.MerchantUserBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantInfoBaseService;
import com.ojoin.trade.common_core.web.service.TransferTokenStatusService;
import com.ojoin.weixin.core.message.model.SendMessage;

@Service
public class AccountBaseServiceImpl implements AccountBaseService {

	@Autowired
	private MerchantUserBaseService userservice;
	
	@Autowired
	private TbMerchantInfoBaseService infoservice;

	@Autowired
	private TransferTokenStatusService tokenService;
	
	@Autowired
	private TransferTokenStatusService transstatusservice;

    @Autowired
    private TbWeekEndService tbWeekEndService;
    
    @Autowired
    private HotConfigService hotConfigService;

    
	private Logger log = LoggerFactory.getLogger(AccountBaseServiceImpl.class);

	@Override
	public List queryBaseAccountBalance(String mhtNo, String accType)
			throws BusinessException {
		Packages packages = new Packages();
		Unpack unpack = new Unpack();
		Map<String, String> map = new HashMap<String, String>();
		List list = null;
		String requestReport = "";
		String funcode = IAccountConst.QUERY_FINANCIALACC_FUC;
		map.put("funcode", funcode);
		map.put("mhtNo", mhtNo);
		map.put("accType", accType);
		requestReport = packages.returnMess(funcode, map);
		requestReport = "requestReport=" + requestReport;
		String xml = HttpPost.http(IAccountConst.IP, requestReport);
		log.info("商户号{},账户类型{}尝试查询余额", new String[] {mhtNo, accType});
		list = unpack.unpack(xml, Constants.ENCODING);
		return list;
	}

    @Override
    public int queryFeeForDraw(String amount) throws BusinessException {
        long restrictamount=IAccountConst.restrictamount;
        if(CommonUtils.isDev()){
            restrictamount=IAccountConst.restrictamount_dev;
        }

       if(isDaySpecial()||!CommonUtils.isWorkTime()){
            int zhengshu=(int)((new BigDecimal(amount).multiply(new BigDecimal(100))).longValue()/restrictamount);
            int mo=(int)((new BigDecimal(amount).multiply(new BigDecimal(100))).longValue()/restrictamount);
            if(mo!=0){
                return zhengshu+1;
            }else{
                return zhengshu;
            }

        }else{
            return 1;
        }




    }



    private  boolean isDaySpecial()throws BusinessException{
        GregorianCalendar calendar=new GregorianCalendar();
        TbWeekend vo=tbWeekEndService.queryWorkDayForWeekend(TimeUtils.getCurDate(), TimeUtils.getCurYear());
        if (calendar.get(GregorianCalendar.DAY_OF_WEEK) != GregorianCalendar.SATURDAY
                && calendar.get(GregorianCalendar.DAY_OF_WEEK) != GregorianCalendar.SUNDAY){
            if(CommonUtils.isEmpty(vo)){
                return false;
            }else{
                return true;
            }
        }else{
            if(CommonUtils.isEmpty(vo)){
                return true;
            }else{
                return false;
            }
        }


    }
    @Override
	public List openFinanceAccount(String mhtNo) throws BusinessException {
		Packages packages = new Packages();
		Unpack unpack = new Unpack();
		Map<String, String> map = new HashMap<String, String>();
		List list = null;
		String requestReport = "";
		String funcode = IAccountConst.FINANCIALACC_FUC;
		map.put("funcode", funcode);
		map.put("mhtNo", mhtNo);
		String orderId = UUIDUtils.create();
		map.put("orderId", orderId);
		requestReport = packages.returnMess(funcode, map);
		requestReport = "requestReport=" + requestReport;
		String xml = HttpPost.http(IAccountConst.IP, requestReport);
		log.info("商户号{},订单号{}, 尝试金融户开户", new String[] { mhtNo, orderId });
		list = unpack.unpack(xml, Constants.ENCODING);
		return list;
	}

	@Override
	public void drawAccountBalance(String mhtNo, String payPasswd,
			String cardId, String amount, String memo) throws BusinessException {
        if(CommonUtils.isEmpty(payPasswd)){
            throw new BusinessException("支付密码不能为空");
        }
        long restrictamount=IAccountConst.restrictamount;
        if(CommonUtils.isDev()){
            restrictamount=IAccountConst.restrictamount_dev;
        }
       if(isDaySpecial()|| !CommonUtils.isWorkTime()){
            if(new Long(amount).longValue()>restrictamount){
                int cishu=(int)(new Long(amount).longValue()/restrictamount);
                long leftamount=new Long(amount).longValue()-restrictamount*cishu;
                for(int i=0;i<cishu;i++){
                    try{
                    	String orderId = UUIDUtils.create();
                        drawBalanceToIpaynow( mhtNo,  payPasswd,
                                cardId,new Long(restrictamount).toString(), orderId, "批量提现");
                    }catch (BusinessException e){
                        LogUtils.error(log,e,"提现失败");
                        throw e;
                       //  failure++;
                    }
                }
                if(leftamount!=0){
                    try{
                    	String orderId = UUIDUtils.create();
                    	drawBalanceToIpaynow( mhtNo,  payPasswd,
                            cardId, new Long(leftamount).toString(),  orderId, "批量提现");
                    }catch (BusinessException e){
                        LogUtils.error(log,e,"提现失败");
                        throw e;
                        //failure++;
                    }
                }
//                if(failure!=0){
//                    throw new BusinessException("批量提现成功的笔数是："+success+";失败的笔数是："+failure+";请稍后再试");
//                }
            }else{
            	String orderId = UUIDUtils.create();
            	drawBalanceToIpaynow( mhtNo,  payPasswd,
                        cardId,  amount,  orderId, memo);
            }
        }else{
        	String orderId = UUIDUtils.create();
            drawBalanceToIpaynow( mhtNo,  payPasswd,
                     cardId,  amount,  orderId, memo);

        }
	}

    public void drawBalanceToIpaynow(String mhtNo, String payPasswd,
                                      String cardId, String amount, String orderId, String memo) throws BusinessException{
//        Packages packages = new Packages();
//        Unpack unpack = new Unpack();
//        Map<String, String> map = new HashMap<String, String>();
//        List list = null;
//        String requestReport = "";
//        String funcode = IAccountConst.WITHDRAWCASH_FUC;
//        String orderId = UUIDUtils.create();
//        map.put("funcode", funcode);
//        map.put("mhtNo", mhtNo);
//        map.put("accType", "AT01");
//        map.put("payPasswd", payPasswd);
//        map.put("cardId", cardId);
//        map.put("amount", amount);
//        map.put("memo", memo);
//        map.put("orderId", orderId);
//        requestReport = packages.returnMess(funcode, map);
//        requestReport = "requestReport=" + requestReport;
//        String xml = HttpPost.http(IAccountConst.IP, requestReport);
//        log.info("商户号{},订单号{},取现金额{},卡{}，尝试提现", new String[] { mhtNo, orderId,
//                amount, cardId });
//        list = unpack.unpack(xml, Constants.ENCODING);
//        if(!CommonUtils.isSuccess(list)){
//            throw new BusinessException("orderid:" + orderId + " " +(String)CommonUtils.buildError(list).getMessage());
//        }

		if (CommonUtils.getLong(amount) == 0)
			throw new BusinessException("提现金额不得为0，请检查.");
		
		Packages packages = new Packages();
		Unpack unpack = new Unpack();
		Map<String, String> map = new HashMap<String, String>();
		List list = null;
		String requestReport = "";
		String accTypeFrom = "AT01";
		String funcode = IAccountConst.WITHDRAWCASH_FUC;
		
		// 初始化tokenstatusvo
		TbTransferTokenStatus status = new TbTransferTokenStatus();
		status.setFromIdOfPaynow(mhtNo);
		status.setToIdOfPaynow(mhtNo);
		status.setAccTypeFrom("AT01");
		status.setAccTypeTo(cardId);
		status.setToken(orderId);
		status.setAmount(amount);
		status.setMemo(memo);
		try {
			map.put("funcode", funcode);
	        map.put("mhtNo", mhtNo);
	        map.put("accType", accTypeFrom);
	        map.put("payPasswd", payPasswd);
	        map.put("cardId", cardId);
	        map.put("amount", amount);
	        map.put("memo", memo);
	        map.put("orderId", orderId);
	        
			requestReport = packages.returnMess(funcode, map);
			requestReport = "requestReport=" + requestReport;
			String xml = HttpPost.http(IAccountConst.IP, requestReport);
			list = unpack.unpack(xml, Constants.ENCODING);
			Map data = null;
			log.info("尝试提现，从商户{},提现到卡{},订单号{},金额{},调用提现接口", new String[] { mhtNo,
					cardId, orderId, amount });
			if (CommonUtils.isSuccess(list)) {
				data = (Map) list.get(1);
				status.setTransstatus(IConstDef.TRANSFERSTATUS_SUCCESS);
				status.setReturnmsg((String) data.get("responseMsg"));
			} else if (CommonUtils.isProcessing(list)) {

                Map querydata=queryAccountTransactionStatus(orderId); //支付本身的系统内调用出现问题导致转账异常，重新查询一次订单号确定转账又没有失败
                String resultstatus=(String)querydata.get("status");
                String resultMsg=(String)querydata.get("msg");
                if(CommonUtils.isEmpty(resultstatus)||"02".equals(resultstatus)){
                    data = (Map) list.get(1);
                    status.setTransstatus(IConstDef.TRANSFERSTATUS_PROCESSING);
                    status.setReturnmsg((String) data.get("responseMsg"));
                    tokenService.insertTransferTokenInfo(status);
                    //发送提醒邮件
                    StringBuffer str = new StringBuffer();
                    str.append("mhtNoFrom：" + mhtNo + "<br/>");
                    str.append("accTypeFrom：" + accTypeFrom + "<br/>");
                    str.append("mhtNoTo：" + mhtNo + "<br/>");
                    str.append("accTypeTo：" + cardId + "<br/>");
                    str.append("amount：" + amount + "<br/>");
                    str.append("orderId：" + orderId + "<br/>");
                    str.append("memo：" + memo + "<br/>");
                    EmailSendUtil.send("guoting@18join.com", "请关注：商户提现返回状态处理中", str.toString());
                    log.info("提现请求异常，从商户{},提现到卡{},订单号{},金额{},返回{},发出报文{}", new String[] {
                            mhtNo, cardId, orderId, amount, JSONUtils.toJSONString(list), requestReport });

                    throw new IPayNowException((String) data.get("responseMsg"));
                }else if(!CommonUtils.isEmpty(resultstatus)&&"00".equals(resultstatus)){
                    status.setTransstatus(IConstDef.TRANSFERSTATUS_SUCCESS);
                    status.setReturnmsg(resultMsg);
                }else if(!CommonUtils.isEmpty(resultstatus)&&"01".equals(resultstatus)){
                    throw new BusinessException(resultMsg);
                }

			} else {
				log.info("提现请求通讯异常，从商户{},提现到卡{},订单号{},金额{},返回{},发出报文{}", new String[] {
						mhtNo, cardId, orderId, amount, JSONUtils.toJSONString(list), requestReport });
				throw new BusinessException((String)CommonUtils.buildError(list).getMessage());
			}
			
			tokenService.insertTransferTokenInfo(status);
			log.info("插入提现日志成功，从商户{},提现到卡{},订单号{},金额{}", new String[] { mhtNo,
					cardId, orderId, amount });
			
			

			//发送提现邮件
	        TbMerchantInfo infovo = infoservice.queryInfoByMhtno(mhtNo);
	        if (infovo != null && infovo.getMchName().equals("深圳市前海现在商业保理有限公司")) {
		        //前海现在提现后自动给财务发送邮件
		        String to=  hotConfigService.getTo();
		        String cc=  hotConfigService.getCc();
		    	// 发送内容
		    	String msgcontent = "提现信息：<br/>商户：" + infovo.getMchName() + "<br/>金额：" + CommonUtils.getFenByString(amount) + "<br/>备注：" +  memo + "<br/><br/>请查收后确认，有问题请及时联系。";
		    	String sub = "前海现在保理户提现通知";
		    	String from = Config.getProperty("mail.from.t1");
		    	String fromshortname = "九盈垫资业务组";
		    	log.info("正在发送邮件 收件人:{} 抄送人:{} 内容:{}", new String[] {to, cc, msgcontent});
		    	
		    	boolean isSuccess = EmailSendUtil
		    			.sendByAttchByte(from, fromshortname, to,cc, sub, msgcontent, null);
		    	
				if (isSuccess) {
					log.info("前海现在保理提现通知邮件发送成功."); 
				} else {
					log.info("前海现在保理提现通知邮件发送失败，请检查."); 
				}
				
				if (!CommonUtils.isDev()) {
					//微信推送提醒信息
					SendMessage.sendMsg(new String[]{"hgc","guoting"},String.format(msgcontent));
				}
	        }
		} catch (Exception e) {
            if(e instanceof IPayNowException){
                throw  e;
            }
			log.info("提现失败，从商户{},提现到卡{},订单号{},金额{},发出报文{}", new String[] { mhtNo,
					cardId, orderId, amount, requestReport });
			status.setTransstatus(IConstDef.TRANSFERSTATUS_FAILED);
			status.setReturnmsg(CommonUtils.getMessageByLeft1000(e.getMessage()));
			tokenService.insertTransferTokenInfo(status);
           	if (e instanceof BusinessException) {
				throw (BusinessException) e;
			} else {
				String errcode = IExceptionCode.CONNECT_CODE;
				String errmsg = "与支付服务器连接异常";
				IPayNowException be = new IPayNowException(errmsg);
				throw be;
			}
		}
		
    }

    @Override
	public List addAccountBalance() throws BusinessException {
		return null;
	}

    //老账户体系是3和6都有，无密码的调6，有密码的调3，新账户体系只有3
	@Override
	public List rechargeAccountBalance(String mhtNoFrom, String accTypeFrom,
			String payPasswd, String mhtNoTo, String accTypeTo, String amount,
			String memo, String orderId) throws BusinessException {
		if (CommonUtils.getLong(amount) == 0)
			throw new BusinessException("转账金额不得为0，请检查.");
		
		String rechargeFuncFlag = Config.getProperty("ipaynow.rechargeFunc");//转账功能是否开启
		if(rechargeFuncFlag.equals("disabled")) {
			log.info("转账功能关闭，模拟转账成功，从商户{},转账到商户{},订单号{},金额{}", new String[] { mhtNoFrom,
					mhtNoTo, orderId, amount });
			return null;
		}
		
		Packages packages = new Packages();
		Unpack unpack = new Unpack();
		Map<String, String> map = new HashMap<String, String>();
		List list = null;
		String requestReport = "";

		// 初始化tokenstatusvo
		TbTransferTokenStatus status = new TbTransferTokenStatus();
		status.setFromIdOfPaynow(mhtNoFrom);
		status.setToIdOfPaynow(mhtNoTo);
		status.setAccTypeFrom(accTypeFrom);
		status.setAccTypeTo(accTypeTo);
		status.setToken(orderId);
		status.setAmount(amount);
		status.setMemo(memo);
		try {
			String funcode = "";
//			if (StringUtils.isEmpty(payPasswd) || IConstDef.PAYNOPWD.equals(payPasswd)) {
//				funcode = IAccountConst.TRANSACC_FUC_NOPWD;
//			} else {
				funcode = IAccountConst.TRANSACC_FUC;
//			}
			map.put("funcode", funcode);
			map.put("mhtNoFrom", mhtNoFrom);
			map.put("accTypeFrom", accTypeFrom);
			if (StringUtils.isEmpty(payPasswd)) {
				map.put("payPasswd", IConstDef.PAYNOPWD);
			} else {
				map.put("payPasswd", payPasswd);
			}
			map.put("mhtNoTo", mhtNoTo);
			map.put("accTypeTo", accTypeTo);
			map.put("amount", amount);
			map.put("memo", memo);
			map.put("orderId", orderId);
			requestReport = packages.returnMess(funcode, map);
			requestReport = "requestReport=" + requestReport;
			String xml = HttpPost.http(IAccountConst.IP, requestReport);
			list = unpack.unpack(xml, Constants.ENCODING);
			Map data = null;
			log.info("尝试转账，从商户{},转账到商户{},订单号{},金额{},调用转账接口", new String[] { mhtNoFrom,
					mhtNoTo, orderId, amount });
			if (CommonUtils.isSuccess(list)) {
				data = (Map) list.get(1);
				status.setTransstatus(IConstDef.TRANSFERSTATUS_SUCCESS);
				status.setReturnmsg((String) data.get("responseMsg"));
			} else if (CommonUtils.isProcessing(list)) {

                Map querydata=queryAccountTransactionStatus(orderId); //支付本身的系统内调用出现问题导致转账异常，重新查询一次订单号确定转账又没有失败
                String resultstatus=(String)querydata.get("status");
                String resultMsg=(String)querydata.get("msg");
                if(CommonUtils.isEmpty(resultstatus)||"02".equals(resultstatus)){
                    data = (Map) list.get(1);
                    status.setTransstatus(IConstDef.TRANSFERSTATUS_PROCESSING);
                    status.setReturnmsg((String) data.get("responseMsg"));
                    tokenService.insertTransferTokenInfo(status);
                    //发送提醒邮件
                    StringBuffer str = new StringBuffer();
                    str.append("mhtNoFrom：" + mhtNoFrom + "<br/>");
                    str.append("accTypeFrom：" + accTypeFrom + "<br/>");
                    str.append("mhtNoTo：" + mhtNoTo + "<br/>");
                    str.append("accTypeTo：" + accTypeTo + "<br/>");
                    str.append("amount：" + amount + "<br/>");
                    str.append("orderId：" + orderId + "<br/>");
                    str.append("memo：" + memo + "<br/>");
                    EmailSendUtil.send("guoting@18join.com", "请关注：商户转账返回状态处理中", str.toString());
                    log.info("转账请求异常，从商户{},转账到商户{},订单号{},金额{},返回{},发出报文{}", new String[] {
                            mhtNoFrom, mhtNoTo, orderId, amount, JSONUtils.toJSONString(list), requestReport });

                    throw new IPayNowException((String) data.get("responseMsg"));
                }else if(!CommonUtils.isEmpty(resultstatus)&&"00".equals(resultstatus)){
                    status.setTransstatus(IConstDef.TRANSFERSTATUS_SUCCESS);
                    status.setReturnmsg(resultMsg);
                }else if(!CommonUtils.isEmpty(resultstatus)&&"01".equals(resultstatus)){
                    throw new BusinessException(resultMsg);
                }

			} else {
				log.info("转账请求通讯异常，从商户{},转账到商户{},订单号{},金额{},返回{},发出报文{}", new String[] {
						mhtNoFrom, mhtNoTo, orderId, amount, JSONUtils.toJSONString(list), requestReport });
				throw new BusinessException((String)CommonUtils.buildError(list).getMessage());
			}
			
			tokenService.insertTransferTokenInfo(status);
			log.info("插入转账日志成功，从商户{},转账到商户{},订单号{},金额{}", new String[] { mhtNoFrom,
					mhtNoTo, orderId, amount });
		} catch (Exception e) {
            if(e instanceof IPayNowException){
                throw  e;
            }
			log.info("转账失败，从商户{},转账到商户{},订单号{},金额{},发出报文{}", new String[] { mhtNoFrom,
					mhtNoTo, orderId, amount, requestReport });
			status.setTransstatus(IConstDef.TRANSFERSTATUS_FAILED);
			status.setReturnmsg(CommonUtils.getMessageByLeft1000(e.getMessage()));
			tokenService.insertTransferTokenInfo(status);
           	if (e instanceof BusinessException) {
				throw (BusinessException) e;
			} else {
				String errcode = IExceptionCode.CONNECT_CODE;
				String errmsg = "与支付服务器连接异常";
				IPayNowException be = new IPayNowException(errmsg);
				throw be;
			}

		}
		return list;
	}

	@Override
	public List queryAccountBaseTransactionDetail(String token)
			throws BusinessException {
		Packages packages = new Packages();
		Unpack unpack = new Unpack();
		Map<String, String> map = new HashMap<String, String>();
		List list = null;
		String requestReport = "";
		String orderId = UUIDUtils.create();
		String funcode = IAccountConst.QUERYTRANS_FUC;
		map.put("funcode", funcode);
		map.put("orderId", token);
		requestReport = packages.returnMess(funcode, map);
		requestReport = "requestReport=" + requestReport;
		String xml = HttpPost.http(IAccountConst.IP, requestReport);
		log.info("商户{},订单号{}查询交易记录，尝试查询账户交易明细", new String[] { token });
		list = unpack.unpack(xml, Constants.ENCODING);
		return list;
	}

    @Override
    public Map<String,String> queryAccountTransactionStatus(String token) throws BusinessException {
     List list=queryAccountBaseTransactionDetail(token);
        Map<String,String> map=new HashMap<>();
        String status;
        String responseMsg;
        String first = (String) list.get(0);
        if ("00".equals(first)) {
            Map<String, String> data = (Map) list.get(1);
            String responseCode = data.get("responseCode");
            responseMsg=data.get("responseMsg");
            map.put("status",responseCode);
            map.put("msg",responseMsg);
    }
        return map;
    }

    @Override
	public String queryBalance(String mhtNo, String accType)
			throws BusinessException {
		List list = queryBaseAccountBalance(mhtNo, accType);
		String account = null;
		Map data = null;

		if (CommonUtils.isSuccess(list)) {
			data = (Map) list.get(1);
			String mhtdatastr = "";
			if (data.get("mhtData") != null) {
				mhtdatastr = (String) data.get("mhtData");
			} else {
				mhtdatastr = (String) data.get("accData");
			}
			
			if (!StringUtils.isEmpty(mhtdatastr)) {
				Map obj = JSONUtils.parseObject(mhtdatastr,
						Map.class);
				if (obj != null && obj.size() > 0) {
					account = obj.get("balance") + "";
				}
			}
		} else {
			throw new BusinessException("mhtno->" + mhtNo + "取" + accType +"余额异常");
		}
		return account;
	}

    @Override
	public String queryBankNo(String mhtNo, String accType)
			throws BusinessException {
		List list = queryBaseAccountBalance(mhtNo, accType);
		Map data = null;

		if (CommonUtils.isSuccess(list)) {
			data = (Map) list.get(1);
			String mhtdatastr = "";
			if (data.get("mhtData") != null) {
				mhtdatastr = (String) data.get("mhtData");
			} else {
				mhtdatastr = (String) data.get("accData");
			}
			
			if (!StringUtils.isEmpty(mhtdatastr)) {
				Map obj = JSONUtils.parseObject(mhtdatastr,
						Map.class);
				if (obj != null && obj.size() > 0) {
					return obj.get("bankNo") + "";
				}
			}
		} else {
			return null;
		}
		return null;
	}
    
	@Override
	public List rechargeAccountBalanceNoPwd(String mhtNoFrom,
			String accTypeFrom, String mhtNoTo, String accTypeTo,
			String amount, String memo, String orderId)
			throws BusinessException {
		return rechargeAccountBalance(mhtNoFrom, accTypeFrom,
				IConstDef.PAYNOPWD, mhtNoTo, accTypeTo, amount, memo, orderId);
	}

	@Override
	public List queryAccountChangeDetail(String mhtNo, String accType,
			String start, String number, String queryData)
			throws BusinessException {
		Packages packages = new Packages();
		Unpack unpack = new Unpack();
		Map<String, String> map = new HashMap<String, String>();
		List list = null;
		String requestReport = "";
		String funcode = IAccountConst.ACC_CHANGE_FUC;
		map.put("funcode", funcode);
		map.put("mhtNo", mhtNo);
		map.put("accType", accType);
		map.put("start", start);
		map.put("number", number);
		map.put("queryData", queryData);
		requestReport = packages.returnMess(funcode, map);
		requestReport = "requestReport=" + requestReport;
		String xml = HttpPost.http(IAccountConst.IP, requestReport);
		log.info("商户{},从第几行{},查询的数目{},尝试查询账户变更记录",
				new String[] { mhtNo, start, number });
		list = unpack.unpack(xml, Constants.ENCODING);
		return list;
	}

	@Override
	public String queryFinanceAccountBankNo(String mhtNo) throws BusinessException {
		List list = queryFinanceAccountInfo(mhtNo);
		Map data = null;

		if (CommonUtils.isSuccess(list)) {
			data = (Map) list.get(1);
			if (data.get("mhtData") != null) {
				String mhtdatastr = (String) data.get("mhtData");
				Map obj = JSONUtils.parseObject(mhtdatastr,
						Map.class);
				if (obj != null) {
					return (String) obj.get("bankNo");
				}
			}
		} else {
			LogUtils.getT0loanLog().info("查询商户{}的业务户账号信息:", new String[] { mhtNo, JSONUtils.toJSONString(list)} );
			throw new BusinessException("查询商户" + mhtNo + "的业务户账号信息出错：" + CommonUtils.buildError(list).getMessage());
		}
		return null;
	}
	
	@Override
	public List queryFinanceAccountInfo(String mhtNo)
			throws BusinessException {
		Packages packages = new Packages();
		Unpack unpack = new Unpack();
		Map<String, String> map = new HashMap<String, String>();
		List list = null;
		String requestReport = "";
		String funcode = IAccountConst.QUERY_FINANCIALACC_FUC;
		map.put("funcode", funcode);
		map.put("mhtNo", mhtNo);
		map.put("accType", IConstDef.ACCTYPE_FINANCING);
		requestReport = packages.returnMess(funcode, map);
		requestReport = "requestReport=" + requestReport;
		String xml = HttpPost.http(IAccountConst.IP, requestReport);
		log.info("查询商户{}，尝试查询商户结算户信息", new String[] { mhtNo});
		list = unpack.unpack(xml, Constants.ENCODING);
		
		return list;
	}
	
	@Override
	public Long queryFinanceAccountBanlance(String mhtNo)
			throws BusinessException {
		//测试环境的tc_joinceshi2@sina.com用户默认设值
		if (CommonUtils.isDev() && (
				mhtNo.equals("mchId20160429000000000000000000000000101") || 
				mhtNo.equals("mchId20151224000000000000000000000000601") ||
				mhtNo.equals("mchId20160429000000000000000000000000051")) ) 
			return (long)100000000;
		
		List list = queryFinanceAccountInfo(mhtNo);
		Map data = null;
		
		if (CommonUtils.isSuccess(list)) {
			data = (Map) list.get(1);
			String mhtdatastr = "";
			if (data.get("mhtData") != null) {
				mhtdatastr = (String) data.get("mhtData");
			} else {
				mhtdatastr = (String) data.get("accData");
			}
			if (!StringUtils.isEmpty(mhtdatastr)) {
				log.info("查询商户"+ mhtNo + "结算户信息:" + mhtdatastr);
				Map accmap = JSONUtils.parseObject(mhtdatastr, Map.class);
				if (accmap != null) {
					Object balanceObj = accmap.get("balance");
					if (balanceObj!=null) {
						return new Long((String)balanceObj);
					} else {
						throw new BusinessException("查询商户" + mhtNo + "结算账户信息出错");
					}
				}
			}
		} else {
			log.info("查询商户" + mhtNo + "结算户信息:" + JSONUtils.toJSONString(list) );
			throw new BusinessException("查询商户" + mhtNo + "结算账户信息出错：" + CommonUtils.buildError(list).getMessage());
		}
		return null;
	}
}
